package cn.wolfcode.redis.impl;


import cn.wolfcode.domain.User;
import cn.wolfcode.redis.IUserInfoRedisService;
import cn.wolfcode.redis.util.RedisKeys;
import cn.wolfcode.util.Consts;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {

    //约定: key value都是字符串类型
    @Autowired
    private StringRedisTemplate template;

    @Override
    public void sendVerifyCode(String phone,String code1) {
        // 将code 存入到缓存当中
        String key = RedisKeys.VERIFY_CODE.join(phone);
        String value = code1;
        template.opsForValue().set(key,value, Consts.VERIFY_CODE_VAI_TIME*60,TimeUnit.SECONDS);
    }

    @Override
    public String getVerifyCode(String phone) {
        String key = RedisKeys.VERIFY_CODE.join(phone);
        String code = template.opsForValue().get(key);
        return code;
    }

    @Override
    public String setToken(User user) {
        //以token 为key ,user 对象为 value 缓存到redis 设置有效时间为30分钟
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String key = RedisKeys.USER_TOKEN.join(token);
        String value = JSON.toJSONString(user);
        template.opsForValue().set(key,value,RedisKeys.USER_TOKEN.getTime(),TimeUnit.SECONDS);
        return token;
    }

    @Override
    public User getUserByToken(String token) {
        // 判断token 是否为空
        if (!StringUtils.hasLength(token)){
            return null;
        }
        String key = RedisKeys.USER_TOKEN.join(token);

        if (template.hasKey(key)){
            // 获得的对象时json 格式的user 对象
            String userStr = template.opsForValue().get(key);
            // 将 json 格式的字符串 转成 对象
            User user = JSON.parseObject(userStr, User.class);
            // 重置 30 分钟
            template.expire(key,RedisKeys.USER_TOKEN.getTime(), TimeUnit.SECONDS);
            return  user;
        }
        return null;
    }

    @Override
    public User getUserInfoByToken(String token) {
        String user = template.opsForValue().get(RedisKeys.USER_TOKEN.join(token));
        return JSON.parseObject(user,User.class);
    }
}
